package com.seed.launcher.listener.wifi;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

/**
 * @author xct
 * create on: 2022/8/31 17:04
 */
public class WifiUtil {

    public static final int SECURITY_NONE = 0;
    public static final int SECURITY_WEP = 1;
    public static final int SECURITY_PSK = 2;
    public static final int SECURITY_EAP = 3;
    public static final int SECURITY_OWE = 4;
    public static final int SECURITY_SAE = 5;
    public static final int SECURITY_EAP_SUITE_B = 6;
    public static final int SECURITY_EAP_WPA3_ENTERPRISE = 7;
    public static final int SECURITY_MAX_VAL = 8; // Has to be the last
    public static int getSecurity(Context context, ScanResult result) {
        final boolean isWep = result.capabilities.contains("WEP");
        final boolean isSae = result.capabilities.contains("SAE");
        final boolean isPsk = result.capabilities.contains("PSK");
        final boolean isEapSuiteB192 = result.capabilities.contains("EAP_SUITE_B_192");
        final boolean isEap = result.capabilities.contains("EAP");
        final boolean isOwe = result.capabilities.contains("OWE");
        final boolean isOweTransition = result.capabilities.contains("OWE_TRANSITION");

        if (isSae && isPsk) {
            final WifiManager wifiManager = (WifiManager)
                    context.getSystemService(Context.WIFI_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                return wifiManager.isWpa3SaeSupported() ? SECURITY_SAE : SECURITY_PSK;
            }
        }
        if (isOweTransition) {
            final WifiManager wifiManager = (WifiManager)
                    context.getSystemService(Context.WIFI_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                return wifiManager.isEnhancedOpenSupported() ? SECURITY_OWE : SECURITY_NONE;
            }
        }

        if (isWep) {
            return SECURITY_WEP;
        } else if (isSae) {
            return SECURITY_SAE;
        } else if (isPsk) {
            return SECURITY_PSK;
        } else if (isEapSuiteB192) {
            return SECURITY_EAP_SUITE_B;
        } else if (isEap) {
            return SECURITY_EAP;
        } else if (isOwe) {
            return SECURITY_OWE;
        }
        return SECURITY_NONE;
    }


    public static final String KEY_PREFIX_AP = "AP:";
    public static String getKey(String ssid, String bssid, int security) {
        StringBuilder builder = new StringBuilder();
        builder.append(KEY_PREFIX_AP);
        if (TextUtils.isEmpty(ssid)) {
            builder.append(bssid);
        } else {
            builder.append(ssid);
        }
        builder.append(',').append(security);
        return builder.toString();
    }
}
